package com.wxx.service.tool.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.wxx.util.AppUtil;
import com.wxx.util.PropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class QiNiuServiceImpl implements QiNiuService {
    private static final String accessKey = PropertiesUtil.getProperty("QINIU_KEY");
    private static final String secretKey = PropertiesUtil.getProperty("QINIU_SECRET");
    private static final String bucket = PropertiesUtil.getProperty("QINIU_BUCKET");

    Map maps =null;
    @Override
    public String getUpToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    @Override
    public Map uploadPhoto(MultipartFile file) {
        maps = new HashMap();
        //上传到七牛后保存的文件名
        String key = AppUtil.uuid() + ".png";
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
                //解析上传成功的结果
                maps  = new Gson().fromJson(response.bodyString(),Map.class);
                maps.put("code",200);
            } catch (QiniuException ex) {
                maps.put("code",500);
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            maps.put("code",500);
            //ignore
        } catch (IOException e) {
            maps.put("code",500);
            e.printStackTrace();
        }

        return maps;
    }

    @Override
    public Map uploadMovie(MultipartFile file) {
        return null;
    }
}
